# -*- coding: utf-8 -*-
import sys
import Image
from PySide import QtGui
# from PySide import QtCore
import rc


class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.init_data()
        self.init_ui()

    def init_data(self):
        self.width = 300
        self.font_size = 5
        self.image_file_name = ''

    def init_ui(self):
        self.setWindowTitle(u'字符画工具')
        self.setWindowIcon(QtGui.QIcon(':/image/1.png'))
        open_action = QtGui.QAction(u'打开(&O)', self)
        open_action.setShortcut("Ctrl+O")
        open_action.triggered.connect(self.open)
        exit_action = QtGui.QAction(u'退出(&X)', self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        set_width_action = QtGui.QAction(u'图像宽度', self)
        set_width_action.setShortcut("Ctrl+W")
        set_width_action.triggered.connect(self.set_width)
        set_font_size_action = QtGui.QAction(u'字体大小', self)
        set_font_size_action.setShortcut("Ctrl+S")
        set_font_size_action.triggered.connect(self.set_font_size)
        about_action = QtGui.QAction(u'关于(&A)', self)
        about_action.setShortcut("Ctrl+A")
        about_action.triggered.connect(self.about)

        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu(u"文件(&F)")
        file_menu.addAction(open_action)
        file_menu.addSeparator()
        file_menu.addAction(exit_action)
        setting_menu = menu_bar.addMenu(u"设置(&S)")
        setting_menu.addAction(set_width_action)
        setting_menu.addAction(set_font_size_action)
        help_menu = menu_bar.addMenu(u"帮助(&H)")
        help_menu.addAction(about_action)

        self.out = QtGui.QPlainTextEdit()
        self.out.setReadOnly(True)
        self.out.setWordWrapMode(QtGui.QTextOption.NoWrap)
        self.out.setFont(QtGui.QFont(u'新宋体', self.font_size))
        self.setCentralWidget(self.out)

    def open(self):
        self.image_file_name, _ = QtGui.QFileDialog.getOpenFileName(self, u'打开图片', '.', u'图片文件 (*.png *.bmp *.jpg)')
        if len(self.image_file_name) != 0:
            self.out.setPlainText(self.get_ascii_str(self.image_file_name))

    def set_width(self):
        width, ok = QtGui.QInputDialog.getInteger(self, u'设置字符图宽度', u'范围(300~500)', self.width, 100, 500, 10)
        if not ok:
            return
        self.width = width
        if len(self.image_file_name) != 0:
            self.out.setPlainText(self.get_ascii_str(self.image_file_name))

    def set_font_size(self):
        size, ok = QtGui.QInputDialog.getInteger(self, u'设置字符大小', u'范围(1~10)', self.font_size, 5, 12, 1)
        if not ok:
            return
        self.font_size = size
        self.out.setFont(QtGui.QFont(u'新宋体', self.font_size))
        if len(self.image_file_name) != 0:
            self.out.setPlainText(self.get_ascii_str(self.image_file_name))

    def about(self):
        QtGui.QMessageBox.information(self, u'关于此程序', u'此程序功能为把图像转成字符画<br><br>    作者:zhangjia_86@126.com')

    def get_ascii_str(self, image_file_name):
        pattern = ''.join(map(lambda x: x * 16, 'MNHQ$OC?7>!:-;. '))
        im = Image.open(image_file_name).convert('L')
        width, height = self.width, 0
        dw = self.out.fontMetrics().width('..') - self.out.fontMetrics().width('.')
        dh = self.out.fontMetrics().lineSpacing()
        height = im.size[1] * width / im.size[0]
        im = im.resize((width, height * dw / dh))  # 此处必须考虑行间距和字间距, 不然会导致图像比例失调
        im_str = ''.join([pattern[im.getpixel((x, y))] for y in range(im.size[1]) for x in range(im.size[0])])
        return '\n'.join(im_str[i: i + im.size[0]] for i in range(0, len(im_str), im.size[0]))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.showMaximized()
    sys.exit(app.exec_())
